package com.example.test.agent.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.test.agent.dto.LoginDTO;
import com.example.test.agent.dto.SaveUserDTO;
import com.example.test.agent.entity.BaseResult;
import com.example.test.agent.entity.User;
import com.example.test.agent.service.UserService;
import com.example.test.utils.ProjectUtil;
import com.example.test.utils.RandCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Api(tags = "用户管理模块")
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<Object, Object> myRedisTemplate;

    @ApiOperation("根据用户ID获取用户信息")
    @GetMapping("/queryValueById")
    public BaseResult<User> queryValueById(@RequestParam("userId") @ApiParam(name = "userId", value = "用户ID", required = true) Integer userId){
        User user = userService.getById(userId);
        myRedisTemplate.opsForValue().set("userInfo", user, 60, TimeUnit.SECONDS);
        return BaseResult.success(user);
    }

    @ApiOperation("根据用户命查询相应的用户")
    @GetMapping("/queryValueByUserName")
    public BaseResult queryValueByUserName(@RequestParam("userName") @ApiParam(name = "userName", value = "用户名", required = true) String userName){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("user_name", userName);
        List<User> userList = userService.list(wrapper);
        return BaseResult.success(userList);
    }

    @ApiOperation("新增用户信息")
    @PostMapping("/saveValue")
    public BaseResult saveValue(@RequestBody @Valid SaveUserDTO saveUserDTO){
        return userService.saveValue(saveUserDTO);
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public BaseResult login(@RequestBody @Valid LoginDTO loginDTO){
        boolean checkResult = RandCodeUtil.validate(loginDTO.getCode(), myRedisTemplate);
        //如果验证码通过，执行登陆操作
        if(checkResult){
            return userService.login(loginDTO);
        }
        return BaseResult.errorMsg("验证码错误");
    }


    @ApiOperation("获取用户列表")
    @GetMapping("/queryPage")
    public BaseResult queryPage(){
        return userService.queryPage();
    }


}
